Skip to content

Add timed wait to sys.thread.Condition - #13109

Merged
Simn merged 15 commits into
developmentfrom
claude/jolly-wozniak-93trgh
Nov 6, 2026
Merged

Simn merged 15 commits into
developmentfrom
claude/jolly-wozniak-93trgh

Conversation

@Simn

@Simn Simn commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Adds a timed wait to sys.thread.Condition on every threaded target. The native changes it uses are all merged (HaxeFoundation/hxcpp#1456, HaxeFoundation/hashlink#1008, HaxeFoundation/neko#336), and CI uses the default branches of hxcpp and HashLink again.

API

function wait():Void;                     // unchanged
function timedWait(timeout:Float):Bool;   // new
  • wait() keeps its signature and documentation. Following Semaphore (blocking acquire():Void plus a separate tryAcquire(?timeout):Bool), the timed variant is a separate method whose result always means something.
  • timeout is relative and in seconds.
  • Returns false only if the timeout expired, and true when signalled or on a spurious wakeup.
  • The internal mutex is always held again on return, timeout included.
  • A timeout of zero or less doesn't block meaningfully (NaN counts as 0). Very large values are clamped instead of overflowing. A wait cut short by a platform limit counts as a spurious wakeup, never as a timeout.

Per-target work

  • Declare the API and document it in std/sys/thread/Condition.hx
  • python: threading.Condition.wait(timeout), clamped to threading.TIMEOUT_MAX, above which Python raises OverflowError. That limit is about 49 days on Windows.
  • jvm: Condition.await(nanos, TimeUnit.NANOSECONDS), like Semaphore.tryAcquire. Each wait is capped at 9e6 s, because Int64.fromFloat throws above 2^53 ns. A capped wait that runs out counts as a spurious wakeup.
  • hl: uses condition_timed_wait, which HashLink has had since at least 1.12. The Haxe side clamps the timeout itself, because older runtimes don't.
  • neko: uses cond_timed_wait ([std] Add cond_timed_wait primitive neko#336, merged) when the runtime has it. Otherwise, for example on Neko 2.4.1 and older, it polls with growing sleeps (at most 10 ms) and a counter that signal/broadcast increment, so it can tell a real notification from a timeout.
    • Haxe CI uses prebuilt neko_latest binaries, so it switches from the fallback to the native primitive once a build that includes [std] Add cond_timed_wait primitive neko#336 is published. That native wait uses a monotonic clock.
  • cpp: uses ConditionVariable::timedWait(double) from Add timedWait to ConditionVariable hxcpp#1456 (merged)
  • eval: Luv.Mutex and Luv.Condition, like Lock and Semaphore since [eval] Use libuv mutex and condition for Lock and Semaphore #13110, so timedWait is a real timed wait and doesn't poll.
    • libuv's mutex is recursive on Windows and calls abort() on misuse elsewhere, so the owning eval thread is tracked. The mutex stays non-recursive on every platform. Acquiring it twice, or releasing or waiting without holding it, throws a Haxe exception instead of aborting or undefined behaviour.

Tests (tests/threads/src/cases/TestCondition.hx)

  • A wait that times out eventually returns false and the mutex is still held (it loops, since a single wait may wake spuriously)
  • A signal inside a predicate loop with a generous deadline wakes the waiter
  • timedWait(0), timedWait(-1) and timedWait(NaN) return false
  • A huge timeout really blocks until signalled, instead of overflowing
  • Run hxcoro's eval suites. They pass locally with the eval implementation, though hxcoro doesn't use Condition itself.

Follow-ups (out of scope)

  • Lock.wait(?timeout):Bool, Semaphore.tryAcquire(?timeout):Bool and Condition.timedWait(timeout):Bool now have three different shapes. Making them consistent could be a separate step.
  • HashLink's hl_semaphore_try_acquire and hl_lock_wait have the same timeout overflow that Fix timeout handling in hl_condition_timed_wait hashlink#1008 fixed in hl_condition_timed_wait, which can serve as their reference.
  • HashLink's timed waits, and Neko's lock_wait, compute deadlines from gettimeofday, the wall clock. [std] Add cond_timed_wait primitive neko#336 shows the monotonic replacement: CLOCK_MONOTONIC via pthread_condattr_setclock, and pthread_cond_timedwait_relative_np on macOS.
  • The mutex behind Condition is recursive on hl, jvm and python but not on cpp, neko and eval. Specifying it as non-recursive would need changes on those targets.
  • In hxcpp, CountingSemaphore.apple.cpp truncates the timeout to whole seconds before converting it.
  • jvm's Semaphore.tryAcquire uses the same Int64.fromFloat conversion, so it throws for timeouts above about 104 days.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

Declare `wait(?timeout:Float):Bool` and document its semantics. The
target implementations follow in later commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
Use the new hxcpp `ConditionVariable::timedWait`, and install the hxcpp
branch that adds it in CI until HaxeFoundation/hxcpp#1456 is merged.

Add thread tests for timed waits: timing out with the mutex still held,
being signaled, non-positive and NaN timeouts, and huge timeouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
hl uses the existing `condition_timed_wait` native and clamps the timeout
itself, because older runtimes don't. CI builds the HashLink branch with
the native fixes until HaxeFoundation/hashlink#1008 is merged.

neko uses the new `cond_timed_wait` primitive when it is available
(HaxeFoundation/neko#336), and otherwise polls with growing sleeps,
using a counter that `signal` and `broadcast` increment to detect
notifications.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
The build job's xmldoc step checks every target's std against the core
API, so jvm and python must implement the new signature before CI can
run any tests.

- jvm: Condition.await with nanoseconds, like Semaphore.tryAcquire.
- python: threading.Condition.wait, clamped to threading.TIMEOUT_MAX,
  above which Python raises an OverflowError.
- eval: OCaml's Condition has no timed wait, so poll with growing sleeps
  like StdLock.wait and detect notifications with a counter that
  signal and broadcast increment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
The docgen job builds dox for cpp, which includes sys.thread.Condition,
and installs hxcpp separately from the cpp tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
@Simn

Simn commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

I'm fine with the change in the context of this PR, but could you check again if there's really no way to have a cross-platform non-polling wait for Eval? I know that it's tricky because Windows is weird, but let's take another look at this.

Simn commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

I looked again. There is a non-polling option that works on every platform: back eval's Condition with Luv.Mutex and Luv.Condition instead of OCaml's Mutex and Condition.

  • It doesn't hold the runtime lock while blocked. In luv, the uv_cond_wait, uv_cond_timedwait and uv_mutex_lock bindings are in the Blocking group of luv_c_function_descriptions.ml. generate_c_functions.ml generates that group with ~concurrency:Cstubs.unlocked, so those calls release the OCaml runtime lock while they block, in Thread, LuvThread and Domain mode. trylock and unlock don't block and use the normal stubs.
  • It's a real timed wait on every platform. uv_cond_timedwait uses SleepConditionVariableCS on Windows, pthread_cond_timedwait with CLOCK_MONOTONIC on Linux and pthread_cond_timedwait_relative_np on macOS. It returns ETIMEDOUT on timeout, which Luv.Condition.timedwait returns as Error ETIMEDOUT`. As a bonus, the timeout is measured on a monotonic clock, unlike the hl/neko code.
  • No new dependency. luv is already required by haxe.opam, and evalLuv.ml already wraps these exact functions for eval.luv.Condition.

The change would be confined to StdCondition and vcondition:

  • cmutex : Luv.Mutex.t and cond : Luv.Condition.t, created with init at construction and destroyed in a Gc.finalise.
  • acquire/tryAcquire/release use Luv.Mutex.lock/trylock/unlock.
  • wait() uses Luv.Condition.wait. wait(timeout) uses Luv.Condition.timedwait with the clamped timeout in nanoseconds and maps Error ETIMEDOUTtofalse`.
  • The cgeneration counter and the polling loop go away.

One thing to note: Luv.Mutex isn't recursive, which matches today's OCaml Mutex. I'd still run the eval thread tests in all three dispatcher modes.

I'm happy to switch to this in this PR. CI exercises eval on Linux, macOS and Windows, so we'd find out straight away. Or I can do it in a follow-up.


Generated by Claude Code

Int64.fromFloat throws for values above 2^53, so a timeout above about
104 days threw while the mutex was held, and testTimedWaitHuge hung.
Cap the wait at 9e6 seconds and report a capped wait that runs out as a
spurious wakeup instead of a timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
Replace the polling timed wait with Luv.Condition.timedwait, like Lock
and Semaphore since #13110, which also removes the notification counter.

libuv's mutex is recursive on Windows and aborts the process on misuse on
POSIX, while OCaml's mutex raised Sys_error. Track the owning eval thread
so that the mutex stays non-recursive on every platform and acquiring
twice, or releasing or waiting without holding the mutex, throws a Haxe
exception instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

Simn commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

eval's Condition no longer polls (77a3879, on top of a merge of development that brings in #13110). It now uses Luv.Mutex/Luv.Condition like Lock and Semaphore, with the trylock fast path and the per-wait cap for Windows.

It addresses the two Condition-specific risks from the #13110 discussion: libuv's Windows mutex being recursive, and libuv calling abort() on misuse. The owning eval thread is tracked, so on every platform:

  • tryAcquire while already holding the mutex returns false.
  • acquire while holding it, and release/wait without holding it (including from another thread), throw a Haxe exception, e.g. Condition.release: the mutex is not held by the current thread. Before, OCaml's Mutex raised Sys_error.

Tested locally:

  • tests/threads with --interp: 159 assertions, all OK, including the new TestCondition cases.
  • wait(1.0) takes 1000 ms wall time and 0 ms CPU.
  • A stress test with 4 producers and 4 consumers moving 40k items using wait(0.005): 3 runs, every item received exactly once, ~0.3 s each.
  • hxcoro's eval suites: 369/369 with each dispatcher and in debug, thread tests 3/3, callstack tests 15/15, all examples.

Generated by Claude Code

@Simn

Simn commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

In #13110 we had this:

"Windows does something weird." It did. uv_cond_timedwait on Windows calls SleepConditionVariableCS(..., (DWORD)(timeout / 1e6)), so my 1e9 s clamp overflowed the DWORD. ada7739 caps each wait at 2e6 s, and the loop waits again for the remaining time.

Could you check if this also applies to any of the related PRs here?

Simn commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

I checked every Windows path. None of them overflows, but two of them reported a timeout too early. Both are now fixed:

Target Windows timed wait Status
hl (HaxeFoundation/hashlink#1008) SleepConditionVariableCS, DWORD ms Already clamped to INFINITE - 1 (~49.7 days), so no overflow. But a capped wait that ran out returned false although the requested timeout hadn't expired. Fixed in d5fdf00: it now returns true, as a spurious wakeup.
neko (HaxeFoundation/neko#336) SleepConditionVariableSRW, DWORD ms Same as hl. Fixed in 9c587b9.
cpp (HaxeFoundation/hxcpp#1456) std::condition_variable_any::wait_for Fine. MSVC's STL clamps the relative time itself, and a clamped wait returns cv_status::no_timeout ("Spuriously wake due to clamped timeout" in <condition_variable>), so timedWait returns true. MinGW builds go through winpthreads' timespec API, which has no DWORD.
eval (this PR) uv_cond_timedwait Fine. It reuses the per-wait cap of 2e6 s from #13110: on timeout, Lock/Semaphore wait again for the rest, and Condition returns true for a capped wait.
jvm, python Condition.await / threading.Condition.wait No DWORD involved. jvm caps each wait at 9e6 s with the same spurious-wakeup rule, and python clamps to threading.TIMEOUT_MAX.

So now every target reports false only when the requested time has really passed, and a wait cut short by a platform limit looks like a spurious wakeup, which callers have to handle anyway.

I compiled the new Windows branches of HashLink and Neko with x86_64-w64-mingw32-gcc -fsyntax-only. Their Linux builds and Neko's cond_timed_wait ctest still pass. The 49.7-day case itself can't reasonably be tested in CI.


Generated by Claude Code

HaxeFoundation/hashlink#1008 has been merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
@Simn

Simn commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

Just confirming, was the change to the HL PR something to consider for the neko or hxcpp PRs too?

Simn commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

Yes for Neko; it's already done. hxcpp doesn't need it.

  • Neko ([std] Add cond_timed_wait primitive neko#336): it had the identical Windows branch, so I made the same change there at the same time as HashLink, in e19fa8d (return capped && GetLastError() == ERROR_TIMEOUT; after a failed SleepConditionVariableSRW). Windows and POSIX now both return false for any non-timeout error, and true only for success or a capped wait. Its CI passed.
  • hxcpp (Add timedWait to ConditionVariable hxcpp#1456): there's no equivalent error path. std::condition_variable_any::wait_for doesn't report errors through its return value; it throws std::system_error. timedWait only maps cv_status::no_timeout to true and cv_status::timeout to false. MSVC's STL already reports a clamped wait as no_timeout, so the capped case is a spurious wakeup there too. Nothing to change.

Generated by Claude Code

HaxeFoundation/hxcpp#1456 has been merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
On Windows, MSVC's condition_variable_any::wait_for reports no_timeout
when the OS wait returns slightly before the deadline, so a single
wait(0.1) can return true. The API allows that as a spurious wakeup, so
wait in a loop until a timeout is reported, like callers are expected to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
@Simn
Simn marked this pull request as ready for review November 6, 2026 13:12
@Simn

Simn commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

I need a sanity check on the recursive mutex situation. Does this really only apply to Eval on Windows?

Simn commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

No, it's broader than that. Eval on Windows was only where this PR would have introduced recursion (libuv's uv_mutex_t is a CRITICAL_SECTION there). Across targets, the mutex behind Condition already differs. I checked the sources:

Target Lock behind Condition Recursive?
hl Windows: CRITICAL_SECTION; POSIX: pthread_mutex explicitly set to PTHREAD_MUTEX_RECURSIVE in hl_condition_alloc yes, on all platforms
jvm ReentrantLock yes
python threading.Condition(), whose default lock is an RLock yes
cpp std::mutex in hxcpp's ConditionVariable no (re-locking is UB, in practice a deadlock)
neko Windows: SRWLOCK; POSIX: default pthread_mutex no (re-locking deadlocks)
eval before this PR: OCaml 5 Mutex (error-checking); now: libuv mutex + owner tracking no (re-locking raises)

This PR keeps eval non-recursive, as it was before, on every platform. It doesn't change any other target's recursion.

The differences also affect wait when the lock is held more than once. jvm (await) and python (RLock._release_save) release every hold while waiting and restore them afterwards. On hl, pthread_cond_wait and SleepConditionVariableCS release only one level of a recursive lock, so another thread can't acquire it to signal, and the wait can deadlock. So code that relies on recursion is already unportable today.

If we want a defined behaviour, I'd specify Condition as non-recursive in its documentation, as testTryAcquire's comment already wishes. Making the targets follow it would be a follow-up:

  • hl: drop PTHREAD_MUTEX_RECURSIVE, and add an owner check on Windows, as eval does here. That's a HashLink change.
  • jvm: check lock.isHeldByCurrentThread() in acquire, and make tryAcquire return false in that case.
  • python: pass a plain threading.Lock() to threading.Condition.
  • cpp/neko: already non-recursive. They could turn the deadlock into an exception with an owner check, like eval.

I'd keep that out of this PR, which doesn't change how locking behaves.


Generated by Claude Code

Comment thread std/neko/_std/sys/thread/Condition.hx Resolved
Comment thread std/sys/thread/Condition.hx Resolved
As discussed in review: wait() keeps its original signature and
documentation, and the timed variant becomes timedWait(timeout):Bool,
whose result always means something. This follows Semaphore, which has a
blocking acquire():Void and a separate tryAcquire(?timeout):Bool.

The target implementations are unchanged apart from the split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

Simn commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

windows64-test (js) failed on b3a7741, but not because of this PR. The JS job compiles hxcoro master for the server tests, and hxcoro now uses the CallStackHandler API that development introduced in #13146 (renamed from ExceptionHandler). This branch didn't have that yet, so hxcoro.elements.DefaultCallStackHandler no longer matched haxe.coro.context.IElement.

Fixed by merging development (cac9f9c), with no conflicts. Locally, tests/server now compiles against hxcoro master (e8e26f8), and the eval thread tests still pass.


Generated by Claude Code

@Simn
Simn requested a review from tobil4sk November 6, 2026 15:36
Comment thread std/sys/thread/Condition.hx Resolved
Relax the documentation: very large timeouts may be cut short at a
target-specific limit, and such a wait returns true. Make python, cpp,
hl and neko return true when the timeout exceeds their cap, as jvm and
eval already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
@Simn
Simn merged commit 74c5b46 into development Nov 6, 2026
37 of 38 checks passed
@Simn
Simn deleted the claude/jolly-wozniak-93trgh branch November 6, 2026 15:51
Simn added a commit to HaxeFoundation/hxcoro that referenced this pull request Nov 6, 2026
* Use Condition.timedWait in WakeUpFlag

sys.thread.Condition got a timed wait in HaxeFoundation/haxe#13109, so
WakeUpFlag can block on a condition variable instead of a semaphore. This
removes the invariant that exactly one permit exists while the state isn't
Unset: clear() no longer has to take a permit that a racing setter may
not have released yet, and requestWakeUp() becomes a single exchange
instead of a CAS loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXGMZFfSGDAqgHttxSU

* Fold the timed wait into WakeUpFlag.waitUntil

Both schedulers already loop around waitUntil, recomputing the due time
after every return, so the wait itself doesn't need its own loop for
spurious wake-ups and the remaining time. waitUntil now waits once and
may return early, which replaces waitAndClear and tryWaitAndClear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXGMZFfSGDAqgHttxSU

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants